package castledefense.logic.units;

import castledefense.data.BuildingData;
import castledefense.data.UnitData;
import castledefense.game.screens.MainGameScreen;

public class UnitGenerator {

	private static final int lowestTimeBetweenSpawn = 1500;

	private int timeBetweenSpawn = 8 * 1000;
	private int timeBeforeNextSpawn = 0 * timeBetweenSpawn;
	private final int spawnTimeFactor = 60;

	private int timeBetweenLevel = 25 * 1000;
	private int timeBeforeNextLevel = timeBetweenLevel;

	private int level = 1;

	private MainGameScreen state;

	public UnitGenerator(MainGameScreen state) {
		this.state = state;
	}

	public int getLevel() {
		return level;
	}	

	public int getLevelTime() {
		return timeBeforeNextLevel;
	}

	public void update(int deltaTime) {
		timeBeforeNextSpawn -= deltaTime;
		if (timeBeforeNextSpawn < 0) {
			timeBeforeNextSpawn = timeBetweenSpawn;
			for (int i = 0; i < 4; i++) {
				generateEnemy();
			}
		}

		timeBeforeNextLevel -= deltaTime;
		if (timeBeforeNextLevel < 0) {
			level++;
			BuildingData.money += BuildingData.moneyGeneration;
			if (timeBetweenSpawn > lowestTimeBetweenSpawn)
				timeBetweenSpawn -= spawnTimeFactor;

			timeBeforeNextLevel = timeBetweenLevel;
			for (int i = 0; i < 4; i++) {
				UnitData.levelUp(i);
			}
		}
	}

	private int count = 0;

	private void generateEnemy() {
		if (UnitData.isLife[count]){
		int x = 0;
		int y = 0;
		if (count == 0) {
			x = 0;
			y = (int) (Math.random() * state.getMapSizeY());
		} else if (count == 1) {
			x = state.getMapSizeX() - 1;
			y = (int) (Math.random() * state.getMapSizeY());
		} else if (count == 2) {
			x = (int) (Math.random() * state.getMapSizeX());
			y = 0;
		} else if (count == 3) {
			x = (int) (Math.random() * state.getMapSizeX());
			y = state.getMapSizeY() - 1;
		}
		state.getMap().addUnit(new Unit(x, y, count, state.getMap()));
		}
		count = (count + 1) % 4;
	}

}
